<template>
    <div class="content_list_container">
        <div class="content_list">
            <div class="actions">
                <button @click="addContent">添加内容</button>
                <button @click="deleteSelected">删除选中</button>
            </div>
            <table>
                <thead>
                    <tr>
                        <th><input type="checkbox" v-model="selectAll" @change="toggleSelectAll" /> 全选</th>
                        <th>序号</th>
                        <th>标题</th>
                        <th>类型</th>
                        <th>难度</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="content in contents" :key="content.id">
                        <td><input type="checkbox" v-model="selectedContents" :value="content.content_id" /></td>
                        <td>{{ content.content_id }}</td>
                        <td>{{ content.title }}</td>
                        <td>{{ content.type }}</td>
                        <td>{{ getGradeLevel(content.difficulty) }}</td>
                        <td class="action-buttons">
                            <button @click="viewContent(content.content_id)">查看</button>
                            <button @click="editContent(content.content_id)">编辑</button>
                            <button @click="deleteContent(content.content_id)">删除</button>
                        </td>
                    </tr>
                </tbody>
            </table>

            <!-- 分页组件 -->
            <div class="pagination">
                <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
                <span>第 {{ currentPage }} 页 / 共 {{ pagination.total_pages }} 页</span>
                <button @click="nextPage" :disabled="currentPage === pagination.total_pages">下一页</button>
            </div>
        </div>

        <!-- 查看模态框 -->
        <el-dialog v-model="viewDialogVisible" :title="content.title || '内容详情'" width="50%" @close="closeViewModal">
            <div class="content-detail">
                <el-descriptions :column="1">
                    <el-descriptions-item label="内容">{{ content.text }}</el-descriptions-item>
                    <el-descriptions-item label="拼音">{{ content.pinyin || '无' }}</el-descriptions-item>
                    <el-descriptions-item label="翻译">{{ content.translation }}</el-descriptions-item>
                    <el-descriptions-item label="类型">
                        <el-tag :type="getContentTypeTag(content.type)">{{ content.type }}</el-tag>
                    </el-descriptions-item>
                </el-descriptions>
            </div>

            <template #footer>
                <el-button @click="closeViewModal">关闭</el-button>
            </template>
        </el-dialog>

        <!-- 编辑模态框 -->

        <!-- 编辑对话框 -->
        <el-dialog v-model="editDialogVisible" :title="editableContent.content_id ? '编辑内容' : '新增内容'" width="50%"
            @closed="resetForm">
            <el-form ref="editForm" :model="editableContent" label-width="80px" label-position="top">
                <el-form-item label="标题" prop="title" required>
                    <el-input v-model="editableContent.title" placeholder="请输入标题" />
                </el-form-item>

                <el-form-item label="内容" prop="text" required>
                    <el-input v-model="editableContent.text" type="textarea" :rows="5" placeholder="请输入内容" />
                </el-form-item>

                <el-form-item label="拼音" prop="pinyin">
                    <el-input v-model="editableContent.pinyin" placeholder="请输入拼音" />
                </el-form-item>

                <el-form-item label="翻译" prop="translation">
                    <el-input v-model="editableContent.translation" placeholder="请输入翻译" />
                </el-form-item>

                <el-form-item label="类型" prop="type" required>
                    <el-select v-model="editableContent.type" placeholder="请选择类型">
                        <el-option label="字词" value="字词" />
                        <el-option label="诗词" value="诗词" />
                        <el-option label="英文" value="英文" />
                        <el-option label="其它" value="其它" />
                    </el-select>
                </el-form-item>
                <el-form-item label="难度" prop="difficulty" required>
                    <el-select v-model="editableContent.difficulty" placeholder="请选择难度">
                        <el-option label="一年级" value="1" />
                        <el-option label="二年级" value="2" />
                        <el-option label="三年级" value="3" />
                        <el-option label="四年级" value="4" />
                        <el-option label="五年级" value="5" />
                        <el-option label="六年级" value="6" />
                    </el-select>
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="closeEditModal">取消</el-button>
                <el-button type="primary" @click="saveEditedContent" :loading="isSaving">
                    保存
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ApiService } from '@/api/apiService';
import {
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElSelect,
    ElOption,
    ElButton,
    ElMessage
} from 'element-plus'
import { useUserStore } from '@/stores/user';
const userStore = useUserStore()
const currentUserId = userStore.getUser?.user_id; // 当前登录id
const editDialogVisible = ref(false)// 控制编辑模态框显示
const isSaving = ref(false)
const editForm = ref(null)
const isViewModalVisible = ref(false); // 控制查看模态框显示
const editableContent = ref({
})

const contents = ref([]);
const pagination = ref({});
// 分页相关状态
const currentPage = ref(1);
const pageSize = ref(10); // 每页显示 10 条数据
const content = ref({});
const getGradeLevel = (difficulty) => {
    const gradeLevels = ['一年级', '二年级', '三年级', '四年级', '五年级', '六年级'];
    return gradeLevels[difficulty - 1] || difficulty;
}
async function fetchContents() {
    try {
        const response = await ApiService.getContents(currentPage.value, pageSize.value);
        contents.value = response.data.data.contents;
        pagination.value = response.data.data.pagination;
    } catch (error) {
        console.error('Error fetching contents:', error);
    }
}


// 初始化时加载数据
onMounted(() => {
    fetchContents();
});
// 关闭查看模态框
const closeViewModal = () => {
    viewDialogVisible.value = false
};
// 添加内容
const addContent = () => {
    editableContent.value = {
        title: '',
        text: '',
        pinyin: '',
        translation: '',
        type: '字词',
        difficulty: '1'
    };
    editDialogVisible.value = true;
};


// 编辑学习内容
const editContent = async (content_id) => {

    const response = await ApiService.get_content_by_id(content_id)

    editableContent.value = { ...response.data.data };
    console.log(response.data.data)
    editDialogVisible.value = true

}
const saveEditedContent = async () => {
    try {
        isSaving.value = true;
        await editForm.value.validate();

        const requestData = {
            title: editableContent.value.title,
            text: editableContent.value.text,
            pinyin: editableContent.value.pinyin,
            translation: editableContent.value.translation,
            difficulty: editableContent.value.difficulty,
            type: editableContent.value.type,
            user_id: currentUserId // 当前登录用户ID
        };

        // 使用通用方法，content_id 为 undefined 或 null 时表示新增
        const response = await ApiService.update_content(
            editableContent.value.content_id || null,
            requestData
        );

        if (response.data.code === 200) {
            ElMessage.success(editableContent.value.content_id ? '内容更新成功' : '内容添加成功');
            editDialogVisible.value = false;
            await fetchContents();
        } else {
            throw new Error(response.data.msg || '操作失败');
        }
    } catch (error) {
        ElMessage.error(error.message || '操作失败');
    } finally {
        isSaving.value = false;
    }
};
// 重置表单
const resetForm = () => {
    editForm.value?.resetFields()
}
// 关闭编辑模态框
const closeEditModal = () => {
    editDialogVisible.value = false
}
const viewDialogVisible = ref(false)

// 查看学习内容
const viewContent = async (content_id) => {
    console.log('查看学习内容:', content_id)
    try {
        const response = await ApiService.get_content_by_id(content_id)
        console.log(response)
        if (response.data.code === 200) {
            content.value = response.data.data
            viewDialogVisible.value = true
        } else {
            ElMessage.error(response.data.msg || '获取内容失败')
        }
    } catch (error) {
        console.error('获取内容失败:', error)
        ElMessage.error('获取内容详情时发生错误')
    }
}


// 内容类型标签样式
const getContentTypeTag = (type) => {
    const map = {
        '诗词': 'success',
        '文章': 'warning',
        '词汇': 'primary'
    }
    return map[type] || 'info'
}

// 上一页
const prevPage = () => {
    if (currentPage.value > 1) {
        currentPage.value--;
        fetchContents(); // 重新加载数据
    }
};

// 下一页
const nextPage = () => {
    if (currentPage.value < pagination.value.total_pages) {
        currentPage.value++;
        fetchContents(); // 重新加载数据
    }
};

// 选中的内容ID列表
const selectedContents = ref([]);

// 全选状态
const selectAll = ref(false);

// 全选/取消全选
const toggleSelectAll = () => {
    if (selectAll.value) {
        // 使用 map 方法将 contents 中的所有 content_id 添加到 selectedContents
        selectedContents.value = contents.value.map(content => content.content_id);
    } else {
        selectedContents.value = [];
    }
};

// 删除选中/全选内容
const deleteSelected = async () => {
    if (selectedContents.value.length === 0) {
        ElMessage.warning('请先选择要删除的内容')
        return
    }

    try {
        // 使用Element Plus确认框
        await ElMessageBox.confirm(
            `确定要删除选中的 ${selectedContents.value.length} 个内容吗？此操作不可撤销！`,
            '删除确认',
            {
                confirmButtonText: '确认删除',
                cancelButtonText: '取消',
                type: 'warning',
                customClass: 'delete-confirm-dialog',
                confirmButtonClass: 'el-button--danger',
                beforeClose: async (action, instance, done) => {
                    if (action === 'confirm') {
                        instance.confirmButtonLoading = true
                        try {
                            const response = await ApiService.deleteContents(selectedContents.value)

                            if (response.data.code === 200) {
                                ElMessage.success({
                                    message: `成功删除 ${selectedContents.value.length} 个内容`,
                                    duration: 2000
                                })

                                // 处理页码逻辑
                                if (currentPage.value > 1) {
                                    currentPage.value--
                                }
                            } else {
                                throw new Error(response.data.msg || '删除失败')
                            }

                            // 重置状态
                            selectedContents.value = []
                            selectAll.value = false
                            await fetchContents()
                        } catch (error) {
                            ElMessage.error({
                                message: error.message || '删除过程中发生错误',
                                duration: 3000
                            })
                        } finally {
                            instance.confirmButtonLoading = false
                            done()
                        }
                    } else {
                        done()
                    }
                }
            }
        )
    } catch (error) {
        // 用户点击取消
        if (error !== 'cancel' && error !== 'close') {
            console.error('删除错误:', error)
        }
    }
}


const deleteContent = async (content_id) => {
    try {
        // 使用Element Plus确认框
        await ElMessageBox.confirm(
            '确定要删除这个内容吗？此操作不可撤销！',
            '删除确认',
            {
                confirmButtonText: '确认删除',
                cancelButtonText: '取消',
                type: 'warning',
                customClass: 'delete-confirm-dialog',
                confirmButtonClass: 'el-button--danger',
                beforeClose: async (action, instance, done) => {
                    if (action === 'confirm') {
                        instance.confirmButtonLoading = true
                        try {
                            const response = await ApiService.deleteContent(content_id)
                            console.log('deleteContent', response)
                            if (response.status === 200) {
                                ElMessage.success({
                                    message: '内容已删除',
                                    duration: 2000,
                                    onClose: () => {
                                        // 更新内容列表，移除被删除的内容
                                        contents.value = contents.value.filter(
                                            content => content.content_id !== content_id
                                        )
                                        pagination.value.current_page_count--

                                        if (pagination.value.current_page_count === 0 &&
                                            currentPage.value > 1) {
                                            currentPage.value-- // 减少当前页码
                                        }
                                    }
                                })
                            } else {
                                throw new Error(response.data.msg || '删除失败')
                            }
                        } catch (error) {
                            ElMessage.error({
                                message: error.message || '删除过程中发生错误',
                                duration: 3000
                            })
                        } finally {
                            instance.confirmButtonLoading = false
                            done()
                            await fetchContents() // 重新获取内容
                        }
                    } else {
                        done()
                    }
                }
            }
        )
    } catch (error) {
        // 用户点击取消
        if (error !== 'cancel' && error !== 'close') {
            console.error('删除错误:', error)
        }
    }
}

</script>

<style scoped>
    @import url("@/assets/css/content_list.css");
</style>